package com.qmerak.common;

import java.lang.annotation.Annotation;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

/**
 * 获取spring ioc中的bean
 * 
 * @author hexin
 * 
 */
public class SpringUtil {
	private static ApplicationContext ctx = null;

	// spring 框架容器
	public static ApplicationContext getCtx() {
		return ctx;
	}

	public static void setCtx(ApplicationContext ctx) {
		SpringUtil.ctx = ctx;
	}

	/**
	 * 
	 * @return
	 */
	public static Map<String, Object> getServiceBean() {
		return getAnnotationBean(Service.class);
	}

	private static Map<String, Object> getAnnotationBean(Class<? extends Annotation> annotationType) {
		return ctx.getBeansWithAnnotation(annotationType);
	}

	/**
	 * 按照bean id来获取bean
	 * 
	 * @param beanName
	 * @return
	 */
	public static Object getBean(String beanName) {
		return ctx.getBean(beanName);
	}

	/**
	 * 按照接口 或者实体类class获取bean
	 * 
	 * @param clazz
	 * @return
	 */
	public static <T> T getBean(Class<T> clazz) {
		return ctx.getBean(clazz);
	}

	public static DataSource getDataSource() {
		return (DataSource) getBean("dataSource");
	}
}
